﻿$(function () {

    // initialise the "Select date" link
    $('#date-pick')
        .datePicker(
            // associate the link with a date picker
            {
                createButton: false,
                startDate: '01/01/2005',
                endDate: '31/12/2020'
            }
        ).bind(
            // when the link is clicked display the date picker
            'click',
            function () {
                updateSelects($(this).dpGetSelected()[0]);
                $(this).dpDisplay();
                return false;
            }
        ).bind(
            // when a date is selected update the SELECTs
            'dateSelected',
            function (e, selectedDate, $td, state) {
                updateSelects(selectedDate);
            }
        ).bind(
            'dpClosed',
            function (e, selected) {
                updateSelects(selected[0]);
            }
        );

    var updateSelects = function (selectedDate) {
        var selectedDate = new Date(selectedDate);
        $('#d option[value=' + selectedDate.getDate() + ']').attr('selected', 'selected');
        $('#m option[value=' + (selectedDate.getMonth() + 1) + ']').attr('selected', 'selected');
        $('#y option[value=' + (selectedDate.getFullYear()) + ']').attr('selected', 'selected');
    }
    // listen for when the selects are changed and update the picker
    $('#d, #m, #y')
        .bind(
            'change',
            function () {
                var d = new Date(
                            $('#y').val(),
                            $('#m').val() - 1,
                            $('#d').val()
                        );
                $('#date-pick').dpSetSelected(d.asString());
            }
        );

    // default the position of the selects to today
    var today = new Date();
    updateSelects(today.getTime());

    // and update the datePicker to reflect it...
    $('#d').trigger('change');
});